import {Platform} from 'react-native';
import {check, request, PERMISSIONS, RESULTS} from 'react-native-permissions';
import {init, setLocatingWithReGeocode, Geolocation} from 'react-native-amap-geolocation';
import store from '~/store';
import {saveSystem} from '~/store/system';

let geoTimer = 0;

async function initGeolocation(versionName) {
    // android需要手动获取定位权限
    if (Platform.OS === 'android') {
        let androidRes = await check(PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION);
        if (androidRes !== RESULTS.GRANTED) {
            androidRes = await request(PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION);
            if (androidRes !== RESULTS.GRANTED) {
                return false;
            }
        }
    }
    if (Platform.OS === 'ios') {
        let iosRes = await check(PERMISSIONS.IOS.LOCATION_WHEN_IN_USE);
        if (iosRes !== RESULTS.GRANTED) {
            iosRes = await request(PERMISSIONS.IOS.LOCATION_WHEN_IN_USE);
            if (iosRes !== RESULTS.GRANTED) {
                return false;
            }
        }
    }

    const key_list = {
        dev: {
            ios: '05e2900e6e7230c91a628709b777b333',
            android: '8621e65fbce66df45daaaa578fe531aa',
        },
        owner: {
            ios: 'c1140a0b124aa6c0fcd98abfda140638',
            android: '55322c82dac3b82cb8ddf649e55f5288',
        },
        company: {
            ios: 'd19cfbe4fb7b9c426e6c24d1dd82af19',
            android: 'e3478c6d167a958b0f3087cde0ba02ef',
        },
        bank: {
            ios: 'f0de815a6f283854f786a7b60be06de0',
            android: 'f1859616de487979e6d5a76a2ae4c9f1',
        },
        agent: {
            ios: '3afbde18c267239e45f9ac1c23ac1e58',
            android: '24c54c8600cbc74834a0c18b5df4eb67',
        },
    };

    // 初始化高德地图SDK
    await init(key_list[versionName]);

    // 设定iOS获取定位包含逆地理编码
    if (Platform.OS === 'ios') {
        await setLocatingWithReGeocode(true);
    }
    await setGeoLocation();
    geoTimer = setInterval(() => {
        setGeoLocation();
    }, 5000);
}

async function setGeoLocation() {
    await Geolocation.getCurrentPosition(
        ({location}) => {
            const getters = store.getState();
            let adCode = location.adCode || 0;
            if (getters.system.adcode !== adCode) {
                store.dispatch(
                    saveSystem({
                        adcode: adCode,
                    }),
                );
            }
        },
        (error) => {
            clearInterval(geoTimer);
            console.log(error);
        },
    );
}

export default initGeolocation;
